<template>
  <div class="signup">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="auto"
      class="demo-ruleForm signin-box"
    >
      <div class="title">
        <img src="/images/logo.png" alt />
        <h3>申请成为MMooc讲师</h3>
      </div>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input maxlength="11" v-model="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input type="password" v-model="ruleForm.pass"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="rePass">
        <el-input type="password" v-model="ruleForm.rePass"></el-input>
      </el-form-item>
      <el-form-item class="city" label="所在城市" required>
        <el-form-item class="city-1" prop="province">
          <el-select
            class="input"
            @change="showCityNames"
            v-model="ruleForm.province"
            placeholder="省级地区"
          >
            <el-option v-for="item in provinces" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="city-2" prop="city">
          <el-select
            :disabled="disabledCity"
            class="input"
            v-model="ruleForm.city"
            placeholder="市级地区"
          >
            <el-option v-for="(item,idx) in cityNames" :key="idx" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item label="曾就读于" prop="xueli">
        <el-input maxlength="20" v-model="ruleForm.xueli"></el-input>
      </el-form-item>
      <el-form-item label="期望任教科目" prop="job">
        <el-input v-model="ruleForm.job"></el-input>
      </el-form-item>
      <el-form-item label="民族" prop="minzu">
        <el-select class="input" @change="showCityNames" v-model="ruleForm.minzu" placeholder="民族">
          <el-option v-for="item in minzuData" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="职业经历" prop="zhiyejingli">
        <el-input
          maxlength="160"
          placeholder="请输入职业经历，最多150字"
          type="textarea"
          :rows="3"
          v-model="ruleForm.zhiyejingli"
        ></el-input>
      </el-form-item>
      <el-form-item label="身份证" required>
        <el-upload
          class="upload-demo"
          action
          :on-change="checkShenfenzheng"
          :auto-upload="false"
          list-type="picture-card"
          ref="uploadShenFenZheng"
          :limit="2"
        >
          <i class="el-icon-plus"></i>
          <div slot="tip" class="el-upload__tip">
            请分别上传身份证
            <strong style="font-weight:600;color:#333">正反</strong> 照，只能上传jpg/jpeg/png文件，且不超过2M
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="教师资格证" required>
        <el-upload
          class="upload-demo"
          action
          :on-change="checkZhengjian"
          :auto-upload="false"
          list-type="picture-card"
          :limit="1"
          ref="uploadJiaoShiZiGeZheng"
        >
          <i class="el-icon-plus"></i>
          <div slot="tip" class="el-upload__tip">
            请上传
            <strong style="font-weight:600;color:#333">1张</strong> 教师资格证照片，只能上传jpg/jpeg/png文件，且不超过2M
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="免冠照" required>
        <el-upload
          class="upload-demo"
          action
          :auto-upload="false"
          :on-change="checkMianguanzhao"
          list-type="picture-card"
          :limit="1"
          ref="uploadMianGuanZhao"
        >
          <i class="el-icon-plus"></i>
          <div slot="tip" class="el-upload__tip">
            请上传
            <strong style="font-weight:600;color:#333">1张</strong> 免冠照，只能上传jpg/jpeg/png文件，且不超过2M
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item class="code" label="验证码" prop="code">
        <el-input maxlength="6" class="input" v-model="ruleForm.code"></el-input>
        <el-button
          @click="sendCode"
          type="primary"
          plain
          :disabled="!canSendCode"
          class="sendCode"
          icon="el-icon-s-promotion"
          circle
        ></el-button>
        <div v-show="!canSendCode" class="codeTimer">再次发送 {{codeTimer}} 秒</div>
      </el-form-item>
      <el-form-item class="submit">
        <el-button
          :disabled="btnDisabled"
          :loading="loading"
          class="submitBtn"
          type="primary"
          @click="submitForm('ruleForm')"
        >{{loading?'正在上传': '立即申请'}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  Input,
  Form,
  FormItem,
  Button,
  Select,
  Option,
  Notification,
  Upload
} from "element-ui";
import { getCity,getCode } from "@/api/common";
import { getMinzu, signup } from "@/api/teacher";
import { setInterval, clearInterval } from "timers";
export default {
  components: {
    ElInput: Input,
    ElUpload: Upload,
    ElForm: Form,
    ElFormItem: FormItem,
    ElButton: Button,
    ElSelect: Select,
    ElOption: Option
  },
  data() {
    const validateCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("验证码不能为空"));
      } else if (!value.match(/^[a-zA-Z0-9]{6}$/)) {
        return callback(new Error("验证码为4位字母或数字"));
      }
      return callback();
    };
    const validateUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("用户名不能为空"));
      } else if (!value.match(/^[a-zA-Z0-9\u4e00-\u9fa5]{5,10}$/)) {
        callback(new Error("5-10个中文、字母或数字组合"));
      }
      return callback();
    };
    const validateXueli = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请填写曾就读大学"));
      } else if (!value.match(/^[a-zA-Z0-9\u4e00-\u9fa5]{0,20}$/)) {
        callback(new Error("不能含有特殊字符"));
      }
      return callback();
    };
    const validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("手机号不能为空"));
      } else if (!value.match(/^1[34578]\d{9}$/)) {
        callback(new Error("目前仅支持11位中国大陆手机号"));
      }
      return callback();
    };
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("密码不能为空"));
      } else if (!value.match(/^[a-zA-Z0-9_-]{6,18}$/)) {
        callback(new Error("密码必须为6-18个字母、数字或下划线组合"));
      }
      return callback();
    };
    const validateRePass = (rule, value, callback) => {
      if (value !== this.ruleForm.pass) {
        callback(new Error("两次密码输入不一致"));
      }
      return callback();
    };
    const validateProvince = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选省级地区"));
      }
      return callback();
    };
    const validateCity = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择市级地区"));
      }
      return callback();
    };
    const validateJob = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请填写期望任教科目"));
      } else if (
        value.match(new RegExp("[%--`~@#$^&*=|{}':'\\[\\]<>/~@#￥&*——|{}]"))
      ) {
        callback(new Error("不得含有特殊字符"));
      } else {
        return callback();
      }
    };
    const validateZhiYeJingLi = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请填写职业经历"));
      } else if (
        value.match(new RegExp("[%--`~@#$^&*=|{}':'\\[\\]<>/~@#￥&*——|{}]"))
      ) {
        callback(new Error("不得含有特殊字符"));
      } else {
        return callback();
      }
    };
    const validateMinzu = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择民族"));
      } else {
        return callback();
      }
    };
    return {
      canSendCode: true,
      loading: false,
      btnDisabled: false,
      shenfenzhengFileList: [],
      zhengjianFileList: [],
      mianguanzhaoFileList: [],
      zhengjian: [],
      codeTimer: 10,
      formData: null,
      cityData: {},
      minzuData: {},
      activeProvince: "",
      activeCityName: "",
      provinces: [],
      cityNames: [],
      disabledCity: true,
      ruleForm: {
        province: "",
        city: "",
        xueli: "",
        username: "",
        phone: "",
        pass: "",
        rePass: "",
        minzu: "",
        delivery: false,
        zhiyejingli: "",
        job: "",
        code: ""
      },
      rules: {
        username: [
          { required: true, validator: validateUsername, trigger: "blur" }
        ],
        xueli: [
          { required: true, validator: validateXueli, trigger: "blur" }
        ],
        phone: [{ required: true, validator: validatePhone, trigger: "blur" }],
        pass: [{ required: true, validator: validatePass, trigger: "blur" }],
        rePass: [
          { required: true, validator: validateRePass, trigger: "blur" }
        ],
        code: [{ required: true, validator: validateCode, trigger: "blur" }],
        city: [{ required: true, validator: validateCity, trigger: "change" }],
        province: [
          { required: true, validator: validateProvince, trigger: "change" }
        ],
        job: [{ required: true, validator: validateJob, trigger: "blur" }],
        zhiyejingli: [
          { required: true, validator: validateZhiYeJingLi, trigger: "blur" }
        ],
        minzu: [{ required: true, validator: validateMinzu, trigger: "blur" }]
      }
    };
  },
  methods: {
    sendCode() {
      if (
        !this.ruleForm.phone.match(/^1[34578]\d{9}$/) ||
        !this.ruleForm.username.match(/^[a-zA-Z0-9\u4e00-\u9fa5]{5,10}$/)
      ) {
        Notification.error({
          title: "发送验证码错误",
          message: "请填写正确格式的手机号和用户名"
        });
        return false;
      }
      getCode({
        tel: this.ruleForm.phone,
        username: this.ruleForm.username,
        Identity: 'T'
      }).then(res => {
        let data = res.data;
        if (data.status === 200) {
          this.canSendCode = false;
          let _codeTimer = this.codeTimer;
          let timer = setInterval(() => {
            this.codeTimer--;
            if (this.codeTimer < 0) {
              this.canSendCode = true;
              clearInterval(timer);
              this.codeTimer = _codeTimer;
            }
          }, 1000);
          return true;
        } else {
          Notification.error({
            title: "发送验证码错误",
            message: data.result.msg
          });
          return false;
        }
      });
    },
    checkShenfenzheng(file, fileList) {
      let fileName = file.name;
      let fileSize = file.size / 1024 / 1024;
      let fileType = file.raw.type;
      if (fileSize > 2) {
        Notification.error({
          title: fileName,
          message: "图片大小不得超过2M"
        });
        fileList.splice(fileList.length - 1, 1);
        return false;
      }
      if (!["image/jpeg", "image/jpg", "image/png"].includes(fileType)) {
        Notification.error({
          title: fileName,
          message: "图片只支持JPEG、JPG、PNG格式"
        });
        fileList.splice(fileList.length - 1, 1);
        return false;
      }
      this.shenfenzhengFileList = fileList;
    },
    checkZhengjian(file, fileList) {
      let fileName = file.name;
      let fileSize = file.size / 1024 / 1024;
      let fileType = file.raw.type;
      if (fileSize > 2) {
        Notification.error({
          title: fileName,
          message: "图片大小不得超过2M"
        });
        fileList.splice(fileList.length - 1, 1);
        return false;
      }
      if (!["image/jpeg", "image/jpg", "image/png"].includes(fileType)) {
        Notification.error({
          title: fileName,
          message: "图片只支持JPEG、JPG、PNG格式"
        });
        fileList.splice(fileList.length - 1, 1);
        return false;
      }
      this.zhengjianFileList = fileList;
    },
    checkMianguanzhao(file, fileList) {
      let fileName = file.name;
      let fileSize = file.size / 1024 / 1024;
      let fileType = file.raw.type;
      if (fileSize > 2) {
        Notification.error({
          title: fileName,
          message: "图片大小不得超过2M"
        });
        fileList.splice(fileList.length - 1, 1);
        return false;
      }
      if (!["image/jpeg", "image/jpg", "image/png"].includes(fileType)) {
        Notification.error({
          title: fileName,
          message: "图片只支持JPEG、JPG、PNG格式"
        });
        fileList.splice(fileList.length - 1, 1);
        return false;
      }
      this.mianguanzhaoFileList = fileList;
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let shenfenzhengLength = this.shenfenzhengFileList.length;
          let zhengjianLength = this.zhengjianFileList.length;
          let mianguanzhaoLength = this.mianguanzhaoFileList.length;
          if (shenfenzhengLength !== 2) {
            Notification.error({
              title: "存在一些错误",
              message: "请按照规定上传身份证"
            });
            return false;
          }
          if (zhengjianLength !== 1) {
            Notification.error({
              title: "存在一些错误",
              message: "请按照规定上传教师资格证"
            });
            return false;
          }
          if (mianguanzhaoLength !== 1) {
            Notification.error({
              title: "存在一些错误",
              message: "请按照规定上传免冠照"
            });
            return false;
          }
          for (var pair of this.formData.entries()) {
            if (pair[1].size / 1024 / 1024 > 2) {
              Notification.error({
                title: pair[1].name,
                message: "图片大小不得超过2M"
              });
              return false;
            }
            if (
              !["image/jpeg", "image/jpg", "image/png"].includes(pair[1].type)
            ) {
              Notification.error({
                title: pair[1].name,
                message: "图片只支持JPEG、JPG、PNG格式"
              });
              return false;
            }
          }
          let formData = new FormData();
          formData.append("username", this.ruleForm.username);
          formData.append("password", this.ruleForm.pass);
          formData.append("repassword", this.ruleForm.rePass);
          formData.append("tel", this.ruleForm.phone);
          formData.append("job", this.ruleForm.job);
          formData.append("minzu", this.ruleForm.minzu);
          formData.append(
            "suoshudi",
            this.ruleForm.province + "," + this.ruleForm.city
          );
          formData.append("xueli", this.ruleForm.xueli);
          formData.append("zhiyejingli", this.ruleForm.zhiyejingli);
          formData.append("code", this.ruleForm.code);
          this.shenfenzhengFileList.map(item => {
            formData.append("shenfenzheng[]", item.raw);
          });
          this.zhengjianFileList.map(item => {
            formData.append("zhengjian", item.raw);
          });
          this.mianguanzhaoFileList.map(item => {
            formData.append("mianguanzhao", item.raw);
          });
          let data = formData;
          this.loading = true;
          signup(data).then(res => {
            this.loading = false;
            if (res.status === 200) {
              let data = res.data;
              if (data.status === 200) {
                this.btnDisabled = true;
                Notification.success({
                  title: "上传成功",
                  message: "请等待审核，1个工作日内。"
                });
                return true;
              } else {
                Notification.error({
                  title: "错误",
                  message: data.result.msg
                });
                return false;
              }
            } else {
              Notification.error({
                title: "异常",
                message: "服务器异常，请稍后再试"
              });
              return false;
            }
          });
        } else {
          Notification.error({
            title: "表单",
            message: "请完善表单"
          });
          return false;
        }
      });
    },
    showCityNames() {
      this.disabledCity = false;
      let keys = Object.keys(this.cityData);
      for (let i = 0; i < keys.length; i++) {
        if (this.cityData[keys[i]][0].province === this.ruleForm.province) {
          for (
            let j = 0, k = Object.keys(this.cityData[keys[i]]).length;
            j < k;
            j++
          ) {
            this.cityNames.push(this.cityData[keys[i]][j].name);
          }
          break;
        }
      }
    }
  },
  created() {
    this.formData = new FormData();
    getCity().then(res => {
      this.cityData = res.data;
      let keys = Object.keys(this.cityData);
      for (let i = 0; i < keys.length; i++) {
        this.provinces.push(this.cityData[keys[i]][0].province);
      }
    });
    getMinzu().then(res => {
      this.minzuData = res.data.data.map(item => {
        return item.name;
      });
    });
  }
};
</script>

<style lang="scss" scoped>
@media screen and (min-width: 1200px) {
  .signup {
    width: 100vw;
    height: 100vh;
    position: relative;
    .signup-step {
      position: fixed;
      right: 10%;
      top: 30%;
    }
    .signin-box {
      border: 1px solid rgba($color: #000000, $alpha: 0.2);
      border-radius: 12px;
      margin: 40px auto;
      width: 600px;
      padding: 20px 80px 20px 20px;
      min-height: 500px;
      .title {
        padding: 20px 0;
        img {
          width: 200px;
        }
        h3 {
          margin: 10px 0 20px 10px;
          font-size: 20px;
          letter-spacing: 1px;
        }
      }
      .code {
        .input {
          float: left;
          width: 50%;
        }
        .sendCode {
          float: left;
          margin-left: 25px;
        }
        .codeTimer {
          float: left;
          color: #909399;
          padding-left: 20px;
        }
      }
      .submit {
        text-align: center;
        .submitBtn {
          margin-top: 20px;

          width: 100%;
        }
      }

      .city {
        .city-1 {
          float: left;
          width: 230px;
        }
        .city-2 {
          float: left;
          width: 230px;
        }
        .input {
          margin-right: 30px;
        }
      }
    }
  }
}
</style>